package com.example.systemserver.config;

import cn.hutool.core.convert.NumberWithFormat;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.example.systemserver.bean.ResultBean;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Component
@Order(1)
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        servletResponse.setContentType("application/json;charset=utf-8");

        // 获取请求的url 判断是否放行
        String requestURI = httpServletRequest.getRequestURI();
        if (requestURI.equals("/account/login")||requestURI.startsWith("/file/getImage")){
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        // 验证token的有效性
        String token = httpServletRequest.getHeader("token");
        if(token == null){
            //
            ResultBean resultBean = new ResultBean(401, "请先登录", null);
            servletResponse.getWriter().write(JSONUtil.toJsonStr(resultBean));
            return;
        }
        //verify验证成功 verify为 true
        try {
            JWTUtil.verify(token, "1234567".getBytes(StandardCharsets.UTF_8));
            //解析token
            JWT jwt = JWTUtil.parseToken(token);
            Object timeout = jwt.getPayload("timeout");
            NumberWithFormat numberWithFormat = (NumberWithFormat) timeout;
            long timeout1 = numberWithFormat.longValue();
            if (System.currentTimeMillis() > timeout1) {
                throw new RuntimeException("令牌已过期");
            }

        } catch (Exception e) {
            ResultBean resultBean = new ResultBean(401, "无效令牌", null);
            servletResponse.getWriter().write(JSONUtil.toJsonStr(resultBean));
            return;
        }
        //放行
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
